package com.atguigu.activemq.queue.tx;

import lombok.SneakyThrows;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * @Auther 赵乾坤
 * @Date 2021-04-16 17:30
 */
public class JmsConsumer_TX {
    public static final String ACTIVEMQ_URL = "tcp://192.168.200.128:61616";//根据自己的虚拟机写
    public static final String QUEUE_NAME = "tx01";

    public static void main(String[] args) throws JMSException, IOException {

        System.out.println("*******我是2号消费者");

        //1.创建连接工场，按照给定的url地址，采用默认用户名和密码
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2.通过连接工场，获取连接connection并启动访问
        Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();

        //3 创建会话session
        //两个参数，第一个叫事务/第二个叫签收
        Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
        //4 创建目的地（具体是队列还是主题topic）
        Queue queue = session.createQueue(QUEUE_NAME);
        //5.创建消费者
        MessageConsumer messageConsumer = session.createConsumer(queue);

        while (true) {
            TextMessage textMessage = (TextMessage)messageConsumer.receive(4000L);//不见不散  ，不加参数的
            if (null != textMessage) {
                System.out.println("*********消费者接受到消息：" + textMessage.getText());
                textMessage.acknowledge();
            } else {
                break;
            }
        }
        messageConsumer.close();
//        session.commit();
        session.close();
        connection.close();
    }
}
